import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


# img_dir = '../../../../large_data/CV2/lesson/Day07'
# img_name = 'hammer.jpg'
# img_name = 'Moscow.jpeg'
img_dir = '../../../../large_data/pic'
# img_name = 'DSC05039.JPG'
# img_name = 'DSC05022_1.JPG'
# img_name = 'dog.jpg'
img_name = 'dog_bird.jpg'
# img_name = 'football.jpg'
# img_name = 'messi5.jpg'
img_path = os.path.join(img_dir, img_name)

spr = 3
spc = 2
spn = 0
plt.figure(figsize=[8, 8])

sep('load')
img = cv.imread(img_path, cv.IMREAD_GRAYSCALE)
print('original shape', img.shape)
H, W = img.shape
H2 = (H - 1) // 2
W2 = (W - 1) // 2
my_show_img(img, 'ori gray', cmap='gray')

sep('fft')
img_f = img.astype(np.float32)
f = cv.dft(img_f, flags=cv.DFT_COMPLEX_OUTPUT)
f_show = np.log(cv.magnitude(f[:, :, 0], f[:, :, 1]) + 1e-8)
my_show_img(f_show, 'f cv', cmap='gray')

sep('fft shift')
fshift = np.fft.fftshift(f)
fshift_show = np.log(cv.magnitude(fshift[:, :, 0], fshift[:, :, 1]) + 1e-8)
my_show_img(fshift_show, 'f', cmap='gray')

sep('HPF')
fshift_copy = fshift.copy()
fshift[H2-30:H2+30, W2-30:W2+30] = 0
f_inv = np.fft.ifftshift(fshift)
img_inv = cv.idft(f_inv)
img_inv = cv.magnitude(img_inv[:, :, 0], img_inv[:, :, 1])
my_show_img(img_inv, 'img_inv HPF', cmap='gray')

sep('LPF')
fshift = fshift_copy
mask = np.zeros((*img.shape, 2), dtype=np.float32)
mask[H2-30:H2+30, W2-30:W2+30] = 1.
fshift *= mask
f_inv = np.fft.ifftshift(fshift)
img_inv = cv.idft(f_inv)
img_inv = cv.magnitude(img_inv[:, :, 0], img_inv[:, :, 1])
my_show_img(img_inv, 'img_inv LPF', cmap='gray')